package com.design.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.design.dao.UserMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

@RestController
public class CoreController {

	Logger logger = LoggerFactory.getLogger(CoreController.class);
	public static JsonConfig dateFormatConfig = new JsonConfig();
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static {
		dateFormatConfig.registerJsonValueProcessor(Timestamp.class, new JsonValueProcessor() {
			
			@Override
			public Object processObjectValue(String key, Object value, JsonConfig arg2) {
				return process(value);
			}
			
			@Override
			public Object processArrayValue(Object value, JsonConfig arg1) {
				return process(value);
			}
			
			private Object process(Object value) {
		        if (value == null) {
		            return "";
		        } else {
		            return dateFormat.format((Timestamp) value);
		        }
		    }
		});
	}
	
	@Autowired
	private UserMapper userMapper;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/api", produces = "text/json;charset=UTF-8")
	private String user(@RequestParam Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("api user-->session:{}\n{}", request.getRequestedSessionId(), map);

		JSONObject obj = new JSONObject();
		obj.put("code", 1);
		obj.put("desc", "操作成功");
		
		Map<String, String> user;
		if ("login".equals(map.get("fid"))) {
			user = userMapper.login(map);
			if (user == null || user.isEmpty()) {
				obj.put("code", 0);
				obj.put("desc", "用户不存在或密码错误");
				return obj.toString();
			}
			request.getSession().setAttribute("ulogin", user);
		} else {
			user = (Map<String, String>) request.getSession().getAttribute("ulogin");
			if (user == null) {
				obj.put("code", 0);
				obj.put("desc", "用户未登录");
				return obj.toString();
			}
			map.put("username", user.get("username"));
			switch (map.get("fid").toString()) {
				case "jindu"://进度
					List<Map<String, String>> list = userMapper.selectJindu(map);
					obj.put("data", JSONArray.fromObject(list));
					break;
				case "question"://题目
					list = userMapper.selectQuestion(map);
					obj.put("data", JSONArray.fromObject(list, dateFormatConfig));
					break;
				case "go"://答题
					go(map, obj);
					break;
				case "notes"://错题
					list = userMapper.selectnotes(map);
					obj.put("data", JSONArray.fromObject(list, dateFormatConfig));
					break;
				case "logout"://退出
					request.getSession().invalidate();
					break;
				default:
					obj.put("code", 400);
					obj.put("desc", "非法请求");
					break;
			}
		}
		return obj.toString();
	}

	private void go(Map<String, Object> map, JSONObject obj) {
		// 提取数据库题目答案
		Map<String, String> question = userMapper.selectQuestionId(map);
		
		if (question.get("answer").equals(map.get("answer"))) {
			// 回答正确
			map.put("bingo", "1");
			map.put("error", "0");
		} else {
			// 回答错误
			map.put("bingo", "0");
			map.put("error", "1");
			map.put("notes", map.get("id"));
			// 既然这里答错了 是不是该记录错题
			try {
				userMapper.insertnotes(map);
			}catch (Exception e) {
			}
		}
		map.put("kid", question.get("kid"));
		
		userMapper.updateJindu(map);
	}
}
